package com.wiz.web.controllor;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wiz.common.ResponseCode;
import com.wiz.service.HeadquartersService;
import com.wiz.service.StationService;
import com.wiz.to.HQBaseInfoTO;
import com.wiz.to.StationCodeTO;
import com.wiz.to.StationTO;
import com.wiz.util.KeyUtil;
import com.wiz.util.MapUtil;
import com.wiz.vo.CollectionVO;
import com.wiz.vo.ResponResultVO;
import com.wiz.vo.ResponseJsonBody;
import com.wiz.vo.criteria.StationSearchCriteriaTO;

@Controller
@RequestMapping("/station")
public class StationControllor implements ResponseCode{
	private transient final Logger log=LoggerFactory.getLogger(getClass());
	private Gson gson = new GsonBuilder().disableHtmlEscaping().create();
	@Resource
	private StationService stationService;
	@Resource
	private HeadquartersService headquartersService;

	@RequestMapping(value="/toAdd")
	public String toAdd(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId,
			HttpSession session, Model model){
		try {
			HQBaseInfoTO hqBaseInfoTO = headquartersService.gethqsById(hqId);
			model.addAttribute("hqName", hqBaseInfoTO.getHqName());
			model.addAttribute("hqId", hqBaseInfoTO.getHqId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "station/add";
		
	}
	@RequestMapping(value="/add")
	@ResponseBody
	public String add(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId,
			@RequestParam(value = "hqName", required = true) String hqName,
			@RequestParam(value = "stationName", required = true) String stationName,
			@RequestParam(value = "registeredName", required = true) String registeredName,
			@RequestParam(value = "registeredNumber", required = true) String registeredNumber,
			@RequestParam(value = "legalRepresentative", required = true) String legalRepresentative,
			@RequestParam(value = "address", required = true) String address,
			@RequestParam(value = "contactsName", required = true) String contactsName,
			@RequestParam(value = "phoneNum", required = true) String phoneNum,
			@RequestParam(value = "email", required = false) String email,
			@RequestParam(value = "fpCnt", required = false) int fpCnt,
			@RequestParam(value = "dispenserCnt", required = false) int dispenserCnt,
			@RequestParam(value = "dispenserBrand", required = false) String dispenserBrand,
			@RequestParam(value = "memo", required = false) String memo,
			@RequestParam(value = "password", required = false) String password,
			@RequestParam(value = "provinceId", required = true) String provinceId,
			@RequestParam(value = "province", required = true) String province,
			@RequestParam(value = "cityId", required = true) String cityId,
			@RequestParam(value = "city", required = true) String city,
			HttpSession session, Model model){
		ResponseJsonBody json = null;
		String lat = null;
		String lng = null;
		MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;  
        //  获得图片（根据前台的name名称得到上传的文件）   
		MultipartFile saImg  =  multipartRequest.getFile("saImg");
		MultipartFile cdImg  =  multipartRequest.getFile("cdImg");
		MultipartFile tankerImg  =  multipartRequest.getFile("tankerImg");
		MultipartFile hnImg  =  multipartRequest.getFile("hnImg");
		
		MultipartFile CVSImg  =  multipartRequest.getFile("CVSImg");
		MultipartFile WCImg  =  multipartRequest.getFile("WCImg");
		MultipartFile CWImg  =  multipartRequest.getFile("CWImg");
        MultipartFile repairImg  =  multipartRequest.getFile("repairImg");
		try {
			//得到经纬度
			Map<String,Double> jinwei = MapUtil.tencentJinwei(province+city+address);
			if(jinwei != null){
				lat = jinwei.get("lat").toString();
				lng = jinwei.get("lng").toString();
			}
			Date date = new Date();
			StationTO stationTO = new StationTO(hqId, hqName, null, stationName, registeredName,
					registeredNumber, legalRepresentative, address, contactsName, phoneNum, email,
					fpCnt, dispenserCnt, dispenserBrand, lat, lng, memo, date, provinceId,
					province, cityId, city,1,KeyUtil.getActivationCode(),date);
			
			stationService.addStationAddImg(stationTO,saImg,cdImg,tankerImg,hnImg,
					CVSImg,WCImg,CWImg,repairImg);
			json = new ResponseJsonBody("200", "修改成功", "station_list",
					"navTab", "closeCurrent", null, null);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			json = new ResponseJsonBody("300", e.getMessage(), "station_list",
					"navTab", "closeCurrent", null, null);
		}
		return gson.toJson(json);
		
	}
	@RequestMapping(value="/update")
	@ResponseBody
	public String update(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId,
			@RequestParam(value = "hqName", required = true) String hqName,
			@RequestParam(value = "stationId", required = true) String stationId,
			@RequestParam(value = "stationName", required = true) String stationName,
			@RequestParam(value = "registeredName", required = true) String registeredName,
			@RequestParam(value = "registeredNumber", required = true) String registeredNumber,
			@RequestParam(value = "legalRepresentative", required = true) String legalRepresentative,
			@RequestParam(value = "address", required = true) String address,
			@RequestParam(value = "contactsName", required = true) String contactsName,
			@RequestParam(value = "phoneNum", required = true) String phoneNum,
			@RequestParam(value = "email", required = false) String email,
			@RequestParam(value = "fpCnt", required = false) int fpCnt,
			@RequestParam(value = "dispenserCnt", required = false) int dispenserCnt,
			@RequestParam(value = "dispenserBrand", required = false) String dispenserBrand,
			@RequestParam(value = "memo", required = false) String memo,
			@RequestParam(value = "password", required = false) String password,
			@RequestParam(value = "provinceId", required = true) String provinceId,
			@RequestParam(value = "province", required = true) String province,
			@RequestParam(value = "cityId", required = true) String cityId,
			@RequestParam(value = "city", required = true) String city,
			HttpSession session, Model model){
		ResponseJsonBody json = null;
		String lat = null;
		String lng = null;
		MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;  
        //  获得图片（根据前台的name名称得到上传的文件）   
		MultipartFile saImg  =  multipartRequest.getFile("saImg");
		MultipartFile cdImg  =  multipartRequest.getFile("cdImg");
		MultipartFile tankerImg  =  multipartRequest.getFile("tankerImg");
        MultipartFile hnImg  =  multipartRequest.getFile("hnImg");
        MultipartFile CVSImg  =  multipartRequest.getFile("CVSImg");
		MultipartFile WCImg  =  multipartRequest.getFile("WCImg");
		MultipartFile CWImg  =  multipartRequest.getFile("CWImg");
        MultipartFile repairImg  =  multipartRequest.getFile("repairImg");

		try {
			//得到经纬度
			Map<String,Double> jinwei = MapUtil.tencentJinwei(province+city+address);
			if(jinwei != null){
				lat = jinwei.get("lat").toString();
				lng = jinwei.get("lng").toString();
			}
			StationTO stationTO = new StationTO(hqId, hqName, stationId, stationName, registeredName,
					registeredNumber, legalRepresentative, address, contactsName, phoneNum, email,
					fpCnt, dispenserCnt, dispenserBrand, lat, lng, memo, null, provinceId,
					province, cityId, city,1,null,new Date());
			stationService.updateStationAddImg(stationTO,saImg,cdImg,tankerImg,hnImg,
					CVSImg,WCImg,CWImg,repairImg);
		} catch (Exception e) {
			log.error(e.getMessage());
			json = new ResponseJsonBody("300", e.getMessage(), "station_list",
					"navTab", "closeCurrent", null, null);
			return gson.toJson(json);
		}
		json = new ResponseJsonBody("200", "修改成功", "station_list",
				"navTab", "closeCurrent", null, null);
		return gson.toJson(json);
		
	}
	
	/***/
	@RequestMapping(value="/list")
	public String list(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "numPerPage", required = false,defaultValue="10") int pageSize,
			@RequestParam(value = "pageNum", required = false,defaultValue="1") int pageNo,
			@RequestParam(value = "hqName", required = false) String hqName ,//总部名称
			@RequestParam(value = "legalRepresentative", required = false) String legalRepresentative,//法人/代理人
			@RequestParam(value = "contactsName", required = false) String contactsName,//联系人
			@RequestParam(value = "phoneNum", required = false) String phoneNum,//电话
			@RequestParam(value = "provinceId", required = false) String provinceId,
			@RequestParam(value = "cityId", required = false) String cityId,
			HttpSession session, Model model){
		StationSearchCriteriaTO stationSearchCriteriaTO = new StationSearchCriteriaTO(hqName, legalRepresentative,
				contactsName, phoneNum,provinceId,cityId, pageSize, pageNo, (pageNo > 0 && pageSize > 0));
		
		List<StationTO> agentTOs=stationService.getStationsByCriteriaTO(stationSearchCriteriaTO);
		int totalCount=stationService.getStationsCntByCriteriaTO(stationSearchCriteriaTO);
		CollectionVO collectionTO=new CollectionVO(agentTOs, totalCount, pageSize, pageNo);
		model.addAttribute("collectionTO", collectionTO);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNumShow", totalCount/pageSize+((totalCount%pageSize>0)?1:0));
		model.addAttribute("searchCriteria", stationSearchCriteriaTO);
		return "station/list";
		
	}
	/**根据总部id修改油站*/
	@RequestMapping(value="/listByHqId")
	@ResponseBody
	public String listByHqId(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId,
			HttpSession session, Model model){
				return hqId;
		
	}
	@RequestMapping(value="/details")
	public String details(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "stationId", required = true) String stationId,
			HttpSession session, Model model){
		try {
			StationTO stationTO = stationService.getStation(stationId);
			Map<Integer,String> phothos= stationService.getStationPhoto(stationId);
			model.addAttribute("bean", stationTO);
			model.addAttribute("saImg", phothos.get(1));
			model.addAttribute("cdImg", phothos.get(2));
			model.addAttribute("tankerImg", phothos.get(3));
			model.addAttribute("hnImg", phothos.get(4));
			model.addAttribute("CVSImg", phothos.get(5));
			model.addAttribute("WCImg", phothos.get(6));
			model.addAttribute("CWImg", phothos.get(7));
			model.addAttribute("repairImg", phothos.get(8));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "station/details";
		
	}
	@RequestMapping(value="/toUpdate")
	public String toUpdate(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "stationId", required = true) String stationId,
			HttpSession session, Model model){
		try {
			StationTO stationTO = stationService.getStation(stationId);
			Map<Integer,String> phothos= stationService.getStationPhoto(stationId);
			model.addAttribute("bean", stationTO);
			model.addAttribute("saImg", phothos.get(1));
			model.addAttribute("cdImg", phothos.get(2));
			model.addAttribute("tankerImg", phothos.get(3));
			model.addAttribute("hnImg", phothos.get(4));
			model.addAttribute("CVSImg", phothos.get(5));
			model.addAttribute("WCImg", phothos.get(6));
			model.addAttribute("CWImg", phothos.get(7));
			model.addAttribute("repairImg", phothos.get(8));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "station/update";
		
	}
	@RequestMapping(value="/del")
	@ResponseBody
	public String delete(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "stationId", required = true) String stationId,
			HttpSession session, Model model){
		ResponseJsonBody json = null;
		try {
			stationService.remove(stationId);
			json = new ResponseJsonBody("200","删除成功！" , "station_list",
					"", "", "", "");
		} catch (Exception e) {
			json = new ResponseJsonBody("300", e.getMessage(), "station_list",
					"", "", "", "");
			e.printStackTrace();
		}
		return gson.toJson(json) ;
		
	}
	
	@RequestMapping(value="/createCode")
	
	public String createCode(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "stationId", required = true) String stationId,
			HttpSession session, Model model){
		ResponResultVO responResultVO = null;
		String url = null;
		try {
			url = stationService.createCode(stationId);
			responResultVO = new ResponResultVO(200, url);
		} catch (Exception e) {
			responResultVO = new ResponResultVO(300, e.getMessage());
			e.printStackTrace();
		}
		return gson.toJson(responResultVO) ;
	}
	@RequestMapping(value="/listCode")
	@ResponseBody
	public String listCode(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "ids", required = true) String ids,
			HttpSession session, Model model){
		List<StationCodeTO> codeList = null;
		ResponResultVO responResultVO = null;
		try {
			String [] idArray = ids.split(",");
			codeList = stationService.ListCode(Arrays.asList(idArray));
			responResultVO = new ResponResultVO(200, "success", codeList, 0, 0, 0);
		} catch (Exception e) {
			responResultVO = new ResponResultVO(300, e.getMessage());
			e.printStackTrace();
		}
		return gson.toJson(responResultVO) ;
	}
	@RequestMapping(value="/getCode")
	public String getCode(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "stationId", required = true) String stationId,
			HttpSession session, Model model){
		StationCodeTO stationCode = null;
		ResponseJsonBody json = null;
		try {
			stationCode = stationService.getCode(stationId);
			json = new ResponseJsonBody("200",stationCode.getCodeUrl(), "station_list",
					"", "", "", "");
		} catch (Exception e) {
			json = new ResponseJsonBody("300", e.getMessage(), "",
					"station_list", "", "", "");
			e.printStackTrace();
		}
		return gson.toJson(json) ;
	}

}
